import { createPathArr } from '@mintlify/common';
import isAbsoluteUrl from 'is-absolute-url';
import { visit } from 'unist-util-visit';
const isDataString = (str) => str.startsWith('data:');
const removeContentDirectoryPath = (contentDirectoryPath, filePath) => {
    const pathArr = createPathArr(filePath);
    const contentDirectoryPathArr = createPathArr(contentDirectoryPath);
    contentDirectoryPathArr.reverse().forEach((dir, index) => {
        if (pathArr[index] === dir) {
            pathArr.pop();
        }
    });
    return '/' + pathArr.join('/');
};
export const removeContentDirectoryPaths = (contentDirectoryPath) => () => {
    return (tree) => {
        visit(tree, (node) => {
            const n = node;
            if (n.name === 'img' || n.name === 'source') {
                const srcAttr = n.attributes.find((attr) => attr.name === 'src');
                const nodeUrl = srcAttr?.value;
                if (
                // <img/> component
                srcAttr &&
                    nodeUrl &&
                    !isAbsoluteUrl(nodeUrl) &&
                    !isDataString(nodeUrl)) {
                    srcAttr.value = removeContentDirectoryPath(contentDirectoryPath, nodeUrl);
                }
            }
            else if (
            // ![]() format
            n.type === 'image' &&
                n.url &&
                !isAbsoluteUrl(n.url) &&
                !isDataString(n.url)) {
                n.url = removeContentDirectoryPath(contentDirectoryPath, n.url);
            }
        });
        return tree;
    };
};
